package com.tao.anr

import android.util.Log
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.Executors

/**
 * reate by tao on{DATE}
 */
class WaitTaskManager private constructor() {
    var executors = Executors.newCachedThreadPool()
    var taskList = CopyOnWriteArrayList<WaitTask>()

    companion object {
        val manager = WaitTaskManager()
    }


    fun inrunOnWaitTask(lock: AnrInfo, timeOut: Long, call: WaitAnrCall?) {
        val waitTask = WaitTask(lock, timeOut, call)
        taskList.add(waitTask)
        executors.execute(waitTask)
    }

    fun stop() {
        taskList.forEach {
            it.stop()
        }
        taskList.clear()
        executors.shutdownNow()
        executors = Executors.newCachedThreadPool()
    }

    inner class WaitTask(val lock: AnrInfo, val timeOut: Long, var call: WaitAnrCall?) : Runnable {
        override fun run() {
//            Log.e("tag", "waitTask $lock")
            try {
                try {
                    synchronized(lock) {
                        call?.let { it.onWaitStart(lock) }
                        lock.wait(timeOut)
                    }
                } catch (e: Exception) {
//                    e.printStackTrace()
                }
                lock.endTimeOut = System.currentTimeMillis()
                lock.isAnr = lock.endTimeOut - lock.startTime >= timeOut
                call?.let { it.onWait(lock) }
            } finally {
                taskList.remove(this)
            }
        }

        fun stop() {
            call = null
            synchronized(lock) {
                lock.notifyAll()
            }
        }
    }

    interface WaitAnrCall {
        fun onWaitStart(anrInfo: AnrInfo)
        fun onWait(anrInfo: AnrInfo)

    }
}